package com.jiang.thread.thread;

public class ThreadExamples {
	public static void main(String[] args) {
		new TicketThread().doBuyTicket();
//		new ChaseThread().doChaseGame();
	}
}

// 抢票案例，三者共用一个线程抢票
class TicketThread implements Runnable{
	int num = 10;

	@Override
	public void run() {
		while (true) {
			if(num <= 0){
				break;
			}
			try {
				Thread.sleep(300);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "取到第"+ num-- +"张票");
		}
	}

	public void doBuyTicket() {
		TicketThread ticketThread = new TicketThread();
		new Thread(ticketThread, "学生").start();
		new Thread(ticketThread, "黄牛党").start();
		new Thread(ticketThread, "打工人").start();
	}
}

// 龟兔赛跑游戏
class ChaseThread implements Runnable{
	@Override
	public void run() {
		for (int i = 1; i <= 50; i++) {
			if(Thread.currentThread().getName() == "兔子"){
				try {
					Thread.sleep(50);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(i == 30){
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("兔子跑了"+ i +"米");
			}
			if(Thread.currentThread().getName() == "乌龟"){
				try {
					Thread.sleep(100);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("乌龟跑了"+ i +"米");
			}
			if(i == 50){
				System.out.println(Thread.currentThread().getName() + "到达了终点！");
				break;
			}
		}
	}

	void doChaseGame(){
		ChaseThread chaseThread = new ChaseThread();
		new Thread(chaseThread, "兔子").start();
		new Thread(chaseThread, "乌龟").start();
	}
}

